//
//  ComicViewControlBar.swift
//  MovieAppDemo
//
//  Created by yanjin on 2025/2/3.
//

import SwiftUI

struct ComicViewControlBar: View {
    @Environment(\.dismiss) var dismiss
    @Binding var item: MainPica
    @Binding var ep_name: String
    @Binding var showControlBar: Bool
    @Binding var currentIndex: Int
    @Binding var currentAll: Int
    @Binding var selectIndex: Int
    @State var show_eps:Bool = false
    @Binding var ep_id: Int
    @State private var selectedTab = 1 // 当前选中的标签
    @StateObject private var viewModel = ComicDetailViewModel()
    @State private var hasAppeared = false
    @Binding var is_fav: Int
    @StateObject private var viewModelFav = FavModel()
    
    // eps_data 是章节列表数据，ep_id 是当前章节的 ID
    var eps_data: [ComicEps] {
        viewModel.detail?.eps ?? comiceps
    }
    
    // 获取当前章节的索引
    var currentChapterIndex: Int? {
        eps_data.firstIndex(where: { $0.id == ep_id })
    }
    
    // 判断是否存在上一章节和下一章节
    var hasPreviousChapter: Bool {
        if let currentIndex = currentChapterIndex {
            return currentIndex > 0
        }
        return false
    }
    var hasNextChapter: Bool {
        if let currentIndex = currentChapterIndex {
            return currentIndex < eps_data.count - 1
        }
        return false
    }
    
    // 获取上一章节和下一章节的 ep_id
    var previousChapterID: Int? {
        if let currentIndex = currentChapterIndex, currentIndex > 0 {
            return eps_data[currentIndex - 1].id
        }
        return nil
    }
    
    var nextChapterID: Int? {
        if let currentIndex = currentChapterIndex, currentIndex < eps_data.count - 1 {
            return eps_data[currentIndex + 1].id
        }
        return nil
    }
    
    private func updateEpName() {
        if let currentIndex = currentChapterIndex {
            ep_name = eps_data[currentIndex].name
        }
    }

    
    
    
    var body: some View {
        VStack {
            Section {
                if showControlBar {
                    HStack {
                        Button {
                            dismiss()
                        } label: {
                            Image(systemName: "chevron.left")
                                .font(.system(size: 20))
                                .foregroundStyle(.gray)
                                .padding(10)
                        }
                        
                        Text(ep_name)
                            .font(.system(size: 20))
                            .foregroundStyle(.gray)
                            .padding(10)
                        
                        Spacer()
                        Button {
                            withAnimation(.easeInOut(duration: 0.3)) {
                                selectedTab = 1
                                showControlBar = false
                                show_eps.toggle()
                            }
                        } label: {
                            Text("详")
                                .font(.system(size: 20, weight: .bold))
                                .foregroundStyle(.gray)
                                .padding(10)
                        }
                        
                        Button {
                            
                        } label: {
                            Image(systemName: "ellipsis")
                                .font(.system(size: 20, weight: .bold))
                                .foregroundStyle(.gray)
                                .padding(10)
                        }
                        
                    }
                    .frame(maxWidth: .infinity)
                    .background(Color("BgColor1"))
                }
            }
            .transition(.opacity.combined(with: .move(edge: .top)))
            
            Spacer()
            
            Section {
                if showControlBar {
                    VStack(spacing: 0) {
                        if true {
                            HStack {
                                // 判断是否存在上一章节
                                if hasPreviousChapter {
                                    Button {
                                        if let previousID = previousChapterID {
                                            ep_id = previousID
                                        }
                                    } label: {
                                        Text("上一话")
                                            .font(.system(size: 16))
                                            .foregroundStyle(.gray)
                                    }
                                } else {
                                    Text("无上章")
                                        .font(.system(size: 16))
                                        .foregroundStyle(.gray)
                                        .opacity(0.5) // 不可点击时显示灰色
                                }
                                
                                DraggableProgressBar(currentIndex: $currentIndex, currentAll: $currentAll,selectIndex: $selectIndex)
                                    .frame(width: 250)
                                    .padding(.horizontal,10)
                                
                                // 判断是否存在下一章节
                                if hasNextChapter {
                                    Button {
                                        if let nextID = nextChapterID {
                                            ep_id = nextID
                                        }
                                    } label: {
                                        Text("下一话")
                                            .font(.system(size: 16))
                                            .foregroundStyle(.gray)
                                    }
                                } else {
                                    Text("无下章")
                                        .font(.system(size: 16))
                                        .foregroundStyle(.gray)
                                        .opacity(0.5) // 不可点击时显示灰色
                                }
                            }
                            .frame(maxWidth: .infinity)
                            .background(Color("BgColor1"))
                        }
                        
                        HStack {
                            Button {
                                withAnimation(.easeInOut(duration: 0.3)) {
                                    selectedTab = 2
                                    showControlBar = false
                                    show_eps.toggle()
                                }
                                
                            } label: {
                                VStack(spacing:5) {
                                    Image(systemName: "list.clipboard")
                                        .font(.system(size: 20))
                                        .foregroundStyle(.gray)
                                    
                                    Text("目录")
                                        .font(.system(size: 14))
                                        .foregroundStyle(.gray)
                                }
                                .padding(.leading, 30)
                            }
                            
                            
                            Spacer()
                            
                            
                            
                            
                                Button {
                                    viewModelFav.addToFav(mainId:item.id , type: item.type){ success in
                                        is_fav = is_fav == 0 ? 1 : 0
                                    }
                                } label: {
                                    VStack(spacing:5)  {
                                        Image(systemName: is_fav == 0 ? "heart" : "heart.fill")
                                            .font(.system(size: 20))
                                            .foregroundStyle(.gray)
                                        
                                        Text(is_fav == 0 ? "加入收藏" : "已收藏")
                                            .font(.system(size: 14))
                                            .foregroundStyle(.gray)
                                    }
                                }
                            
                            
                            Spacer()
                            
                            VStack(spacing:5)  {
                                Image(systemName: "gearshape")
                                    .font(.system(size: 20))
                                    .foregroundStyle(.gray)
                                
                                Text("设置")
                                    .font(.system(size: 14))
                                    .foregroundStyle(.gray)
                            }
                            .padding(.trailing, 30)
                        }
                        .padding(.top)
                        .frame(maxWidth: .infinity)
                        .background(Color("BgColor1"))
                    }
                }
            }
            .transition(.opacity.combined(with: .move(edge: .bottom)))
        }
        .onChange(of: ep_id) { oldValue, newValue in
                    updateEpName()  // 更新 ep_name，当 ep_id 改变时
                }
        .onAppear {
            if !hasAppeared {
                viewModel.get_detail(main_id: item.id)
                hasAppeared = true
            }
        }
        .sheet(isPresented: $show_eps) {
            ComicViewEps(item:$item, selectedTab:$selectedTab, ep_id: $ep_id,ep_name: $ep_name)
                .background(Color("BgColor1"))
                .presentationDetents([.medium])
                .presentationDragIndicator(.hidden)
        }
    }
}

struct DraggableProgressBar: View {
    @Binding var currentIndex: Int
    @Binding var currentAll: Int
    @State private var progress: CGFloat = 0.0
    let barWidth: CGFloat = 250
    let barHeight: CGFloat = 20
    let circleDiameter: CGFloat = 30
    @Binding var selectIndex: Int
    
    var body: some View {
        VStack {
            ZStack(alignment: .leading) {
                Capsule()
                    .fill(Color.gray.opacity(0.3))
                    .frame(width: barWidth, height: barHeight)
                
                Capsule()
                    .fill(Color.gray.opacity(0.8))
                    .frame(width: progress * barWidth, height: barHeight)
                
                Circle()
                    .fill(Color.white)
                    .shadow(radius: 4)
                    .frame(width: circleDiameter, height: circleDiameter)
                    .offset(x: progress * barWidth - circleDiameter / 2)
                    .gesture(
                        DragGesture()
                            .onChanged { gesture in
                                // 更新拖动时进度条的进度
                                let newProgress = gesture.location.x / barWidth
                                progress = min(max(newProgress, 0), 1)
                                
                                // 更新选中的章节索引，加入平滑动画
                                withAnimation(.easeInOut(duration: 0.1)) {
                                    selectIndex = Int(progress * CGFloat(currentAll - 1))
                                }
                            }
                            .onEnded { gesture in
                                // 手指松开时，确保进度条指针位置精确并动画平滑
                                let finalProgress = gesture.location.x / barWidth
                                progress = min(max(finalProgress, 0), 1)
                                withAnimation(.easeInOut(duration: 0.3)) {
                                    currentIndex = Int(progress * CGFloat(currentAll - 1))
                                }
                            }
                    )
            }
            .padding()
        }
        .onChange(of: currentIndex) { oldValue, newValue in
            // 根据 currentIndex 更新进度条的进度
            withAnimation(.easeInOut(duration: 0.3)) {
                progress = CGFloat(currentIndex) / CGFloat(currentAll - 1)
            }
        }
        .onAppear {
            // 在初始化时设置进度
            progress = CGFloat(currentIndex) / CGFloat(currentAll - 1)
        }
    }
}



#Preview {
    @Previewable @State var item: MainPica = mainpicas[0]
    @Previewable @State var ep_name: String = "章节名称"
    @Previewable @State var showControlBar = true
    @Previewable @State var currentIndex: Int = 0
    @Previewable @State var currentAll = 100
    @Previewable @State var selectIndex: Int = 0
    @Previewable @State var ep_id: Int = 238721
    @Previewable @State var is_fav: Int = 0
    ComicViewControlBar(item:$item,ep_name: $ep_name,showControlBar: $showControlBar, currentIndex: $currentIndex,currentAll: $currentAll,selectIndex: $selectIndex, ep_id: $ep_id,is_fav:$is_fav)
}
